package com.lyhengtongwl.zqsnews.ui.activity;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.lyhengtongwl.zqsnews.App;
import com.lyhengtongwl.zqsnews.R;
import com.lyhengtongwl.zqsnews.base.BaseActivity;
import com.lyhengtongwl.zqsnews.entity.NewsBaseEntity;
import com.lyhengtongwl.zqsnews.myinterface.JsInterface;
import com.lyhengtongwl.zqsnews.net.MyCallback;
import com.lyhengtongwl.zqsnews.net.Task;
import com.lyhengtongwl.zqsnews.utils.AppConfig;
import com.lyhengtongwl.zqsnews.utils.NewsToastUtils;
import com.lyhengtongwl.zqsnews.utils.SPUtils;
import com.lyhengtongwl.zqsnews.utils.ScreenUtil;
import com.lyhengtongwl.zqsnews.utils.TitleBuilder;
import com.lyhengtongwl.zqsnews.widget.CenterDialog;
import com.lyhengtongwl.zqsnews.widget.NewsShare;
import com.tencent.smtt.export.external.interfaces.SslErrorHandler;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class NewsWebDetailActivity extends BaseActivity {
    @BindView(R.id.myProgressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.webView)
    com.tencent.smtt.sdk.WebView webView;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.iv_title_right)
    ImageView iv_title_right;

    private String url;


    private String imgUrl;
    private String title;
    private String articleId;
    //    private String mDns;
    private String articleReadId;
    private boolean isCollect = false;

    @BindView(R.id.ll_bannerAD)
    LinearLayout ll_bannerAD;

    public static void forward(Context context, String url, String imgUrl, String title, String id) {
        Intent intent = new Intent(context, NewsWebDetailActivity.class);
        intent.putExtra("url", url);
        intent.putExtra("imgUrl", imgUrl);
        intent.putExtra("title", title);
        intent.putExtra("id", id);
        context.startActivity(intent);
    }

    public static void forward(Context context, Bundle bundle) {
        Intent intent = new Intent(context, NewsWebDetailActivity.class);
        intent.putExtras(bundle);
        context.startActivity(intent);
    }

    private void processExtraData() {
        Intent it = getIntent();
        Bundle bundle = it.getExtras();
        if (bundle != null) {
            imgUrl = bundle.getString("imgUrl");
            title = bundle.getString("title");
            articleId = bundle.getString("articleId");//AppConfig.getInstance(App.getContext()).get("articleUrl")
            url = AppConfig.getInstance(App.getContext()).get("articleUrl") + "?articleId=" + articleId + "&app=android";
            articleReadId = bundle.getString("articleReadId");
            checkCollect();
            setWebView();
        }

        new TitleBuilder(NewsWebDetailActivity.this).setTitleText(title)
                .setLeftIcoListening(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        finish();
                    }
                });
//        openCSJBanner();
    }

    //在合适的时机，释放广告的资源
    @OnClick({R.id.iv_title_right, R.id.iv_gl, R.id.ll_onlyTS, R.id.ll_forward})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.iv_title_right://收藏文章
                toCollect();
//                iv_title_right.setImageResource(R.drawable.icon_collection_selected);
//                NewsShare.showShareDialog(getSupportFragmentManager(), NewsWebDetailActivity.this, articleId, title, imgUrl);
                break;
            case R.id.iv_gl://赚钱攻略
                startActivity(new Intent(this, NewsWebGLActivity.class).putExtra("url", AppConfig.getInstance(App.getContext()).get("strategyUrl")).putExtra("isDefault", "true"));
                break;
            case R.id.ll_onlyTS://仅需两步
                new CenterDialog(R.layout.moneymake_tips, this, getSupportFragmentManager()).showEarnPrompt(articleId, title, imgUrl);
                break;
            case R.id.ll_forward://立即转发
                NewsShare.showShareDialog(getSupportFragmentManager(), NewsWebDetailActivity.this, articleId, title, imgUrl);
                break;
        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    protected void onResume() {
        super.onResume();
        webView.onResume();
        webView.getSettings().setJavaScriptEnabled(true);
    }

    @SuppressLint("SetJavaScriptEnabled")
    private void setWebView() {
        //WebView加载web资源
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);// 不使用缓存
        webView.addJavascriptInterface(new JsInterface(NewsWebDetailActivity.this), "android");
        String ua = webView.getSettings().getUserAgentString();
        webView.getSettings().setUserAgentString(ua + "android/ts");
        webView.getSettings().setAppCacheEnabled(false);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setDisplayZoomControls(false);//隐藏Zoom缩放按钮
        //解除数据阻止
        webView.getSettings().setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        webView.setWebChromeClient(new WebChromeClient());
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                if (i == 100) {
                    mProgressBar.setVisibility(View.GONE);
                } else {
                    if (mProgressBar.getVisibility() == View.GONE)
                        mProgressBar.setVisibility(View.VISIBLE);
                    mProgressBar.setProgress(i);
                }
                super.onProgressChanged(webView, i);

            }
        });
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //网页在webView中打开
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {//安卓5.0的加载方法
                    view.loadUrl(request.toString());
                } else {//5.0以上的加载方法
                    view.loadUrl(request.getUrl().toString());
                }
                return true;
            }

            @Override
            public void onReceivedSslError(WebView webView, SslErrorHandler sslErrorHandler, com.tencent.smtt.export.external.interfaces.SslError sslError) {
                sslErrorHandler.proceed();  // 接受所有网站的证书
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        //覆盖WebView默认使用第三方或系统默认浏览器打开网页的行为，使网页用WebView打开
        webView.loadUrl(url);
    }

    @Override
    public void setListen() {

    }

    @Override
    public void setTitleBarColor() {
    }

    @Override
    public int intiLayout() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView() {
//        setWebView();
    }

    @Override
    public void initData() {
        processExtraData();
    }

    @Override
    protected void onPause() {
        super.onPause();
        webView.onPause();
        webView.getSettings().setLightTouchEnabled(false);
    }

    @Override
    protected void onDestroy() {
        if (this.webView != null) {
            webView.destroy();
        }
//        if (mTTAd != null) {
//            //调用destroy()方法释放
//            mTTAd.destroy();
//        }
        super.onDestroy();
    }

    //点击进行收藏或取消收藏
    private void toCollect() {
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        String flag;//flag为0时, 取消收藏, flag为1时,进行收藏

        if (isCollect) {
            flag = "0";
        } else {
            flag = "1";
        }
        Task.getApiService().collectArticle(userId, articleReadId, flag).enqueue(new MyCallback<NewsBaseEntity>(NewsWebDetailActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    String data = Integer.parseInt(response.body().getData().toString().split("\\.")[0]) + "";
                    if ("0".equals(data)) {
                        isCollect = true;
                        iv_title_right.setImageResource(R.drawable.icon_collection_selected);
                    } else {
                        isCollect = false;
                        iv_title_right.setImageResource(R.drawable.icon_collection_unselected);
                    }
                    NewsToastUtils.showToast(App.getContext(), response.body().getMsg());
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //查询是否收藏了本篇文章
    private void checkCollect() {
        String userId = SPUtils.get(App.getContext(), "userId", "") + "";
        Task.getApiService().checkCollect(articleReadId, userId).enqueue(new MyCallback<NewsBaseEntity>(NewsWebDetailActivity.this) {
            @Override
            protected void onSuccess(Response<NewsBaseEntity> response) {
                try {
                    if ("1".equals(response.body().getCode())) {
                        String data = Integer.parseInt(response.body().getData().toString().split("\\.")[0]) + "";
                        if ("1".equals(data)) {
                            //表示未收藏了该文章
                            isCollect = false;
                            iv_title_right.setImageResource(R.drawable.icon_collection_unselected);
                        } else {
                            //表示已经收藏了该文章
                            isCollect = true;
                            iv_title_right.setImageResource(R.drawable.icon_collection_selected);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }
}
